package ilearn.job.disserver.sdk.account;

import ilearn.job.disserver.sdk.account.dto.AccountDTO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
@Log4j2
public class AccountCache {

    private static final String AccountDTOKey = "AccountDTOKey";

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    private RestTemplate restTemplate;

    public AccountDTO getAccountById(Long id,boolean bRemote){
        AccountDTO accountDTO = (AccountDTO) redisTemplate.opsForHash()
                .get(AccountDTOKey,String.valueOf(id));
        if (accountDTO != null ){
            return accountDTO;
        }
        if (bRemote){
            accountDTO = getAccountFromRemote(id);
            updateAccount(accountDTO);
        }
        return accountDTO;
    }

    public void deleteAccountById(Long id){
        redisTemplate.opsForHash().delete(AccountDTOKey,id.toString());
    }

    public void updateAccount(AccountDTO accountDTO){
        redisTemplate.opsForHash().put(AccountDTOKey,accountDTO.getId().toString(),accountDTO);
    }

    private AccountDTO getAccountFromRemote(Long accId){
        AccountDTO accountDTO =
                restTemplate.getForObject("http://localhost:10101/getUser?id=" + accId,AccountDTO.class);
        log.info("远程调用获取到账户对象:{}",accountDTO);
        return accountDTO;
    }
}
